<?php

/**
 * 
 */
class Routes extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('routes_model');
        $this->load->model('reports_model');
    }

    public function index() {
        
    }

    public function create() {
        $this->load->view('templates/header');
        $this->load->view('routes/create');
        $this->load->view('templates/footer');
    }

    public function getBasicRoutesStats() {
        $routes = $this->routes_model->fetchBasicRoutesStats();
    }

    public function loadRoute($days) {
        $arr = array();
        $plus = 0;
        $aa = 0;
        $rad = 0;
        $hl = 0;
        $neh = 0;
        $mob = 0;
        $nove_p = array();
        $data['routes'] = $this->input->post('data');
        $data['array_checked'] = $this->input->post('array_checked');

        $data['zac'] = $this->input->post('zac');
        $data['kon'] = $this->input->post('kon');
        if ($data['kon'] == "null")
            $date_to = date('Y-m-d');
        else
            $date_to = date('Y-m-d', strtotime(str_replace(' ', '', $data['kon'])));
        if ($data['zac'] == "null")
            $date_from = date("Y-m-d", strtotime("$date_to -1 days"));
        else
            $date_from = date('Y-m-d', strtotime(str_replace(' ', '', $data['zac'])));
        if (!empty($data['array_checked'])) {
            $reports = $this->reports_model->fetchLast1000Reports($date_from, $date_to);
            if ($data['routes'] != null) { // kvoli predcasnemu kliku (js show)
                foreach ($data['routes'] as $key => $value) {
                    foreach ($reports as $key => $value_r) {

                        if (round($value_r['latitude'], 3) == round($value[1], 3) &&
                                round($value_r['longitude'], 3) == round($value[0], 3)) {

                            if (in_array($value_r['type_id'], $data['array_checked'])) { // len ak chceme vyhladavat (checkboxy)
                                $temp_arr = array();
                                array_push($temp_arr, $value_r['type_id']);
                                array_push($temp_arr, substr($value_r['longitude'], 0, 6));
                                array_push($temp_arr, substr($value_r['latitude'], 0, 6));

                                if (!($this->in_array_r($temp_arr, $nove_p))) { // potriedime..
                                    array_push($nove_p, $temp_arr);
                                }
                            }
                        }
                    }
                    // print_r($nove_p);
                }
            }

            foreach ($nove_p as $key => $value) {


                $reportLatLng = $this->reports_model->fetchReportLatLong($value[2], $value[1], $date_from, $date_to, $value[0]);
                // print_r($reportLatLng);
                if ($reportLatLng != null && (!empty($reportLatLng['avglng']))) { // query na ukazku na item...
                    $plus++;
                    $typ = $this->typeOfReport($value[0]);
                    $arr[$plus][2] = $typ['obr'];
                    // images
                    $img_up = base_url() . "css/images/up.png";
                    $img_down = base_url() . "css/images/down.png";
                    // kvoli x-ku na konci..., ze kolkokrat..
                    if ($days > 0) {
                        $lastOne = $this->reports_model->fetchReportLatLongRounded($value[2], $value[1]);
                        if ($lastOne != null) {
                            $link = base_url("report") . "/" . $lastOne['report_id'] . "-" . url_title($lastOne['street_noaccent']) . "-" . url_title($lastOne['city_noaccent']);
                            $arr[$plus][3] = "<div style='text-align:center;font-weight:bold;padding-bottom: 5px;'>" . $typ['popis'] . "<br/><span style='color:#888811;font-size:11px;font-weight: normal;'>Naposledy viditeľné:<br /> " . $this->dateFormatToSlovak($lastOne['seen']) . "</div>Komentáre: " . $lastOne['n_comments'] . " | <img src='$img_up'> " . $lastOne['n_thumb_ups'] . " | <img src='$img_down'> " . $lastOne['n_thumb_downs'] . "<br />Pravedopodobnosť výskytu udalosti<br /> za vybrané obdobie: " . round(($reportLatLng['coun'] / $days) * 100) . "% (" . $reportLatLng['coun'] . "x)<br />Viac o udalosti: <a style='color:red;' href='$link' target='_blank'>tu (v novom okne)</a>";
                        } else {
                            $arr[$plus][3] = "Pravedopodobnosť výskytu udalosti za vybrané obdobie: " . round(($reportLatLng['coun'] / $days) * 100) . "% (" . $reportLatLng['coun'] . "x)";
                        }
                        $arr[$plus][0] = $reportLatLng['avglng'];
                        $arr[$plus][1] = $reportLatLng['avglat'];
                    } else {
                        $lastOne = $this->reports_model->fetchReportLatLongRounded($value[2], $value[1]);
                        if ($lastOne != null) {
                            $link = base_url("report") . "/" . $lastOne['report_id'] . "-" . url_title($lastOne['street_noaccent']) . "-" . url_title($lastOne['city_noaccent']);
                            $arr[$plus][3] = "<div style='text-align:center;font-weight:bold;padding-bottom: 5px;'>" . $typ['popis'] . "<br/><span style='color:#888811;font-size:11px;font-weight: normal;'>Naposledy viditeľné:<br /> " . $this->dateFormatToSlovak($lastOne['seen']) . "</div>Komentáre: " . $lastOne['n_comments'] . " | <img src='$img_up'> " . $lastOne['n_thumb_ups'] . " | <img src='$img_down'> " . $lastOne['n_thumb_downs'] . "<br />Pravedopodobnosť výskytu udalosti<br /> za vybrané obdobie: " . round(($reportLatLng['coun'] / $days) * 100) . "%<br />Viac o udalosti: <a style='color:red;' href='$link' target='_blank'>tu (v novom okne)</a>";
                        } else {
                            $arr[$plus][3] = "Pravedopodobnosť výskytu udalosti za vybrané obdobie: " . round(($reportLatLng['coun'] / $days) * 100) . "%";
                        }
                        $arr[$plus][0] = $reportLatLng['avglng'];
                        $arr[$plus][1] = $reportLatLng['avglat'];
                    }
                    switch ($value[0]) {
                        case '1': $rad += $reportLatLng['coun'];
                            break;
                        case '2': $hl += $reportLatLng['coun'];
                            break;
                        case '3': $neh += $reportLatLng['coun'];
                            break;
                        case '4': $mob += $reportLatLng['coun'];
                            break;

                        default:
                            # code...
                            break;
                    }
                }
            }

            $jsontext = "{\"markers\":[";
            foreach ($arr as $key => $value) {
                // if ((double)($value[1])!=0){
                $jsontext .= "{\"latitude\": " . (double) ($value[1]) . ", \"longitude\": " . (double) ($value[0]) . ",\"icon\": \"" . $value[2] . "\",\"count\": \"" . $value[3] . "\"},";
                $aa++;
                // }
            }
            $jsontext = substr_replace($jsontext, '', -1);
            $jsontext .= "],";
            $jsontext .= "\"overal_status\":[";
            $bbb['rad'] = $rad;
            $bbb['hl'] = $hl;
            $bbb['neh'] = $neh;
            $bbb['mob'] = $mob;

            $jsontext .= "{\"rad\": " . $rad . ", \"hl\": " . $hl . ",\"neh\": " . $neh . ",\"mob\": " . $mob . "}";

            $jsontext .= "]}";
        }
        ($aa != 0) ? $data['jsontext'] = $jsontext : $data['jsontext'] = "";

        $this->load->view('routes/json', $data);
    }

    public function update_insert() {
        $rad = $this->input->post('rad');
        $hl = $this->input->post('hl');
        $neh = $this->input->post('neh');
        $mob = $this->input->post('mob');
        if ($this->session->userdata("sess_user_id")) {
            $uid = $this->session->userdata("sess_user_id");
            $this->routes_model->update_route_routes($rad, $hl, $neh, $mob, $uid);
        }
    }

    public function insert() {
        // basic
        $kilometres = $this->input->post('kilometres');
        $avg_speed = $this->input->post('avg_speed');
        $time_driven = $this->input->post('time_driven');
        $s_latitude = $this->input->post('s_latitude');
        $s_longitude = $this->input->post('s_longitude');
        $e_latitude = $this->input->post('e_latitude');
        $e_longitude = $this->input->post('e_longitude');

        // * locations
        $start_loc = $this->input->post('start_loc');
        $end_loc = $this->input->post('end_loc');
        $s_street = $this->getStreet($start_loc);
        $s_city = $this->getCity($start_loc);
        $s_state = $this->getState($start_loc);
        $e_street = $this->getStreet($end_loc);
        $e_city = $this->getCity($end_loc);
        $e_state = $this->getState($end_loc);

        $user_id = $this->session->userdata("sess_user_id");

        $this->routes_model->insert($user_id, $kilometres, $avg_speed, $time_driven, $s_latitude, $s_longitude, $e_latitude, $e_longitude, $s_street, $s_city, $s_state, $e_street, $e_city, $e_state);
    }

    private function dateFormatToSlovak($date) {
        return date('d.m.Y H:i', strtotime($date));
    }

    public function getStreet($input) {
        $part = explode(",", $input);
        if (count($part) == 4) {
            return $part[1];
        } else {
            return $part[0];
        }
    }

    public function getCity($input) {
        $part = explode(",", $input);
        if (count($part) == 3) {
            return ltrim($part[1]);
        } else if (count($part) == 4) {
            return ltrim($part[2]);
        } else {
            return null;
        }
    }

    public function getState($input) {
        $part = explode(",", $input);
        if (count($part) == 3) {
            return ltrim($part[2]);
        } else if (count($part) == 4) {
            return ltrim($part[3]);
        } else {
            return ltrim($part[1]);
        }
    }

    public function typeOfReport($type) {
        $popis = "";
        $obr = "";
        switch ($type) {
            case '1':
                $popis = "Radar";
                $obr = "speed.png";
                break;
            case '2':
                $popis = "Policajná hliadka";
                $obr = "police.png";
                break;
            case '3':
                $popis = "Nehoda";
                $obr = "accident.png";
                break;
            case '4':
                $popis = "Mobilný radar";
                $obr = "mobile_radar.png";
                break;
        }
        return array('popis' => $popis, 'obr' => $obr);
    }

    public function kkt() {
        $data['arr'] = $this->reports_model->lolo();
        $this->load->view('welcome_message', $data);
    }

    public function in_array_r($needle, $haystack) {
        $found = false;
        foreach ($haystack as $item) {
            if ($item === $needle) {
                $found = true;
                break;
            } elseif (is_array($item)) {
                $found = $this->in_array_r($needle, $item);
                if ($found) {
                    break;
                }
            }
        }
        return $found;
    }

}

?>